package cn.sollyu.SDCardManager;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Resources.NotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class MainActivity extends Activity {
	private ProgressBar	main_titleProgressBar	;
	private TextView		main_titleTextView		;
	private ListView		main_fileListView		;
	private ImageView		main_backImageView 	;
	
	// 现在路径
	private File nowPathFile;
	// 存放当前文件列表
	private ArrayList<File> filesArrayList ;
	// 存放浏览记录
	//private HashMap<String, ArrayList<File>> hashMap ;
		
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.main_activity);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.main_activity_title );
	
		ReleaseDatabase();
		initControl();
		

		nowPathFile = new File("/sdcard");
		displayFileList("/sdcard");
		
		DatabaseManagerOpenHelper daOpenHelper = new  DatabaseManagerOpenHelper(this);
		daOpenHelper.getReadableDatabase();
		daOpenHelper.close();
    }
	
	private void ReleaseDatabase() {
		File dir = null;
		File file = null;
		
		try
		{
			dir = new File("data/data/" + getPackageName() + "/databases");
			if (!dir.exists() || !dir.isDirectory())
			{
				dir.mkdir();
			}
			file = getDatabasePath("SDCard.db");
			if (!file.exists())
			{
				//if (android.os.Build.VERSION.SDK > 8 )
				InputStream is = null;
				is = getResources().openRawResource(R.raw.sdcard);
					
				FileOutputStream fos = new FileOutputStream(file);
				byte[] buffer = new byte[8192];
				int count = 0;
				while ((count = is.read(buffer)) > 0)
				{
					fos.write(buffer, 0, count);
				}
				fos.close();
				is.close();
			}
		} catch (NotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
	public boolean RootCmd(String cmd) {
		
		Process process = null;
		DataOutputStream os = null;
		try
		{

			process = Runtime.getRuntime().exec("su");
			os = new DataOutputStream(process.getOutputStream());
			
			
			os.writeBytes(cmd + "\n");
			os.writeBytes("exit\n");
			os.flush();
			process.waitFor();
		} catch (Exception e)
		{
			return false;
		} finally
		{
			try
			{
				if (os != null)
				{
					os.close();
				}
				process.destroy();
			} catch (Exception e)
			{}
		}
		return true;
	}
	
	private void displayFileList(final String pathString) {
		final Handler handler;
		final int MSG_UPDATE = 1;
		final int MSG_PRCESS_VALUE =2;
		final int MSG_PRCESS_MAX  = 3;
		final int MSG_PRCESS_VIS =4;
		final int MSG_TITLE = 5;
		

		
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				
				switch (msg.what) {
					case MSG_UPDATE:
						main_fileListView.setAdapter((SimpleAdapter)msg.obj);
						break;
						
					case MSG_PRCESS_VALUE:
						main_titleProgressBar.setProgress((Integer) msg.obj);
						break;	
						
					case MSG_PRCESS_MAX:
						main_titleProgressBar.setMax((Integer) msg.obj);
						break;
						
					case MSG_PRCESS_VIS:
						main_titleProgressBar.setVisibility((Integer) msg.obj);
						break;
						
					case MSG_TITLE:
						main_titleTextView.setText((CharSequence) msg.obj);
						break;
						
					default:
						break;
				}

				super.handleMessage(msg);
			}
			
		};
		
		new Thread()
		{
			@Override
			public void run() {			
			nowPathFile = new File(pathString);
			
			// 仅文件列表
			try
			{
				filesArrayList = ServiceFileManager.gerFileList(nowPathFile.getAbsolutePath());
				
			} catch (Throwable e)
			{
				filesArrayList = new ArrayList<File>();
			}			
			ServiceFileManager.sortByTypeName(filesArrayList);
			
			handler.obtainMessage(MSG_PRCESS_MAX,filesArrayList.size()-1).sendToTarget();			// 设置进度条最大值
			handler.obtainMessage(MSG_PRCESS_VALUE,0).sendToTarget();						// 其实位置为0
			handler.obtainMessage(MSG_PRCESS_VIS,View.VISIBLE).sendToTarget();					// 进度条可见
			
			ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
			for (int i = 0;i< filesArrayList.size();i++)
			{
				String infoString = ServiceDatabaseManager.getInfoString(filesArrayList.get(i).getAbsolutePath(), MainActivity.this);
				
				HashMap<String, Object> map = new HashMap<String, Object>();						
				map.put("name", filesArrayList.get(i).getName());
				map.put("info", infoString.equals(getString(R.string.string_null)) ? "" : infoString);
				map.put("icon", ServiceFileManager.getFileIcon(filesArrayList.get(i).getAbsolutePath()));
				list.add(map);
				
				handler.obtainMessage(MSG_PRCESS_VALUE,i).sendToTarget();
			}
			
			SimpleAdapter simpleAdapter = new SimpleAdapter(MainActivity.this, list, R.layout.main_activity_list_item, new String[] {"name","info","icon"}, new int[] {R.id.main_list_name,R.id.main_list_info,R.id.main_list_icon});
			handler.obtainMessage(MSG_UPDATE,simpleAdapter).sendToTarget();
			
			handler.obtainMessage(MSG_PRCESS_VIS, View.INVISIBLE).sendToTarget();
			
			handler.obtainMessage(MSG_TITLE,nowPathFile.getAbsolutePath()).sendToTarget();
			}
			
		}.start();
		
	}

	private void openFileWithSelectOpener(String pathString) {
	        Intent intent = new Intent();   
	        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);   
	        intent.setAction(android.content.Intent.ACTION_VIEW);   
	        String fileUriString = ServiceFileManager.getFileUriString(pathString);
	        
		intent.setDataAndType(Uri.fromFile(new File(pathString)),fileUriString);   

		startActivity(intent);

	}
	
	private void initControl() {

		main_titleTextView 	= (TextView) findViewById(R.id.main_activity_title_text);
		main_titleProgressBar 	= (ProgressBar) findViewById(R.id.main_activity_title_ProgressBar);
		main_fileListView	 	= (ListView) findViewById(R.id.main_activity_file_listview);
		main_backImageView	= (ImageView) findViewById(R.id.main_activity_back_imageView);
		
		// 标题栏 返回图标 点击事件
		main_backImageView.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				onBackParentPath();
				
			}
		});
		
		// 点击列表事件
		main_fileListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
				LinearLayout linearLayout = (LinearLayout) ((LinearLayout) ((LinearLayout)arg1).getChildAt(0)).getChildAt(1);
				TextView nameTextView = (TextView) linearLayout.getChildAt(0);
				
				String fileNameString =  nameTextView.getText().toString();
				
				openPath(fileNameString);
			}});
		
		// 创建长按事件
		main_fileListView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
			
			public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
//				AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
				
				menu.setHeaderTitle(getString(R.string.main_list_menu_title));
				menu.add(getString(R.string.main_list_menu_open));
				menu.add(getString(R.string.main_list_menu_view));
				menu.add(getString(R.string.main_list_menu_edit));
				menu.add(getString(R.string.main_list_menu_dele));
			}
		});
		
		
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {	
		AdapterContextMenuInfo itemInfo = (AdapterContextMenuInfo)item.getMenuInfo(); 
		LinearLayout linearLayout = (LinearLayout) ((LinearLayout) ((LinearLayout)itemInfo.targetView).getChildAt(0)).getChildAt(1);
		// 当前选择的文件名
		String fileNameString = ((TextView) linearLayout.getChildAt(0)).getText().toString();
		// 当前文件的文件对象
		final File subFile = new File(nowPathFile.getPath() + "/" + fileNameString); 
		
		// 如果为打开
		if (item.toString().equals(getString(R.string.main_list_menu_open)))
		{
			openPath(fileNameString);
		}else if (item.toString().equals(getString(R.string.main_list_menu_edit)))
		{
			Intent intent = new Intent(MainActivity.this, ActivityEdit.class);
			intent.putExtra("nowSelectFile", subFile);
			startActivityForResult(intent, 11);
			//添加界面切换效果，注意只有Android的2.0(SdkVersion版本号为5)以后的版本才支持 
			int version = Integer.valueOf(android.os.Build.VERSION.SDK); 
			if(version >= 5) { 
				overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out); 
			}
		}
		// 如果为查看
		else if (item.toString().equals(getString(R.string.main_list_menu_view)))
		{
			new ActivityViewAlertDialgo(MainActivity.this, subFile).show();
			
		} 
		// 如果为删除
		else if (item.toString().equals(getString(R.string.main_list_menu_dele)))
		{
			Builder alertDialog = new AlertDialog.Builder(this);
			alertDialog.setTitle("提示");
			alertDialog.setIcon(ServiceFileManager.getFileIcon(subFile.getAbsolutePath()));
			alertDialog.setMessage("确认删除 " + subFile.getName() +"?");
			alertDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					if ( ServiceFileManager.delete(subFile.getAbsolutePath(), MainActivity.this) == true)
						displayFileList(nowPathFile.getAbsolutePath());
					
				}
			});
			alertDialog.setNegativeButton("取消", (OnClickListener)null);
			alertDialog.create().show();
			
			
		}
		
		return super.onContextItemSelected(item);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
		if (keyCode == KeyEvent.KEYCODE_BACK  )
		{
			onBackParentPath();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void onBackParentPath() {
		// 如果这个目录为 跟目录就不继续
		if (nowPathFile.getAbsolutePath().equals("/")) 	{
			finish();
			return;
		}
		displayFileList(nowPathFile.getParent());
	}
	
	private void openPath(String fileNameString) {
		File subFile = new File(nowPathFile.getPath() + "/" + fileNameString);
		if (subFile.isDirectory())
		{					
			displayFileList(subFile.getAbsolutePath());
			return ;
		}
		openFileWithSelectOpener(subFile.getAbsolutePath());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		menu.add(getString(R.string.main_menu_onekey)).setIcon(android.R.drawable.ic_menu_delete);
		menu.add(getString(R.string.main_menu_refresh)).setIcon(android.R.drawable.ic_menu_rotate);
		menu.add(getString(R.string.main_menu_share)).setIcon(android.R.drawable.ic_menu_share);
		menu.add(getString(R.string.main_menu_setting)).setIcon(android.R.drawable.ic_menu_preferences);
		menu.add(getString(R.string.main_menu_about)).setIcon(android.R.drawable.ic_menu_info_details);
		menu.add(getString(R.string.main_menu_exit)).setIcon(android.R.drawable.ic_lock_power_off);
		
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		if (item.toString().equals(getString(R.string.main_menu_refresh)))
		{
			displayFileList(nowPathFile.getAbsolutePath());
		}else if (item.toString().equals(getString(R.string.main_menu_exit)))
		{
			finish();
		}else if (item.toString().equals(getString(R.string.main_menu_about)))
		{
			new HelpDialog(this).show();
		}else if (item.toString().equals(getString(R.string.main_menu_onekey)))
		{
			startActivity(new Intent(MainActivity.this, ActivityOneKey.class)) ;
		}else if (item.toString().equals(getString(R.string.main_menu_share)))
		{
			File databaseFile = getDatabasePath("SDCard.db");
			new AlertDialog.Builder(MainActivity.this)
					.setTitle(getString(R.string.main_alert_title))
					.setMessage(
							getString(R.string.main_alert_message_left)
							+ ServiceFileManager.FormetFileSize(databaseFile.length())
							+ getString(R.string.main_alert_message_right))
					.setPositiveButton(getString(R.string.main_alert_ok), new DialogInterface.OnClickListener() {
							
							public void onClick(DialogInterface dialog, int which) {
								new ServiceIntenet(MainActivity.this,getDatabasePath("SDCard.db").getAbsolutePath()).uploadFile();
								
							}
						})
					.setNegativeButton(getString(R.string.main_alert_cancel), null)
					.create().show();
			
		}
		
		
		return super.onOptionsItemSelected(item);
	}


	
	
	

}